package dao.impl;

import bean.dianzan;
import dao.dianzanDao;
import unit.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class dianzanDaoImpl extends DruidUtil implements dianzanDao {
    @Override
    public dianzan select(dianzan ar) {
        int id = ar.getId();
        Connection conn = null;
        PreparedStatement state = null;
        ResultSet rs = null;

        try {
            conn = getConnection();
            state = conn.prepareStatement("select * from thumbup where id=?");
            state.setInt(1, id);
            rs = state.executeQuery();
            while (rs.next()) {
                ar.setId(rs.getInt("id"));
                ar.setThumbupnum(rs.getInt("thumbupnum"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, state, rs);
        }
         return ar;
    }

        @Override
        public dianzan updateThumbupnum (dianzan ar, String ifCancelThumbup){
            Connection conn = null;
            PreparedStatement state = null;
            int rowNumAffected = 0;
            dianzan old = select(ar);
            int previousNum = old.getThumbupnum();
            try {
                conn = getConnection();
                state = conn.prepareStatement("update thumbup set thumbupnum=? where id=? ");
                if (ifCancelThumbup.equals("false")){
                    state.setInt(1,previousNum+1);
                }else if (ifCancelThumbup.equals("true")){
                    state.setInt(1,previousNum-1);
                }
                state.setInt(2,old.getId());
                rowNumAffected = state.executeUpdate();
                if (rowNumAffected <=0){
                    throw new SQLException();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                close(conn,state,null);
            }
            dianzan newAr = select(ar);
            return newAr;
        }
    }

